﻿
using MassTransit;
using SharedMessages.Messages;

namespace OrderService
{
    public class Program
    {
        public static void Main(string[] args)
        {
            var builder = WebApplication.CreateBuilder(args);

            // Add services to the container.

            builder.Services.AddControllers();
            // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
            builder.Services.AddEndpointsApiExplorer();
            builder.Services.AddSwaggerGen();

            builder.Services.AddMassTransit(x =>
            {
                x.UsingRabbitMq((context, cfg) =>
                {
                    cfg.Host("rabbitmq://114.215.192.243", config =>
                    {
                        config.Username("guest");
                        config.Password("cs123456");
                    });


                    //cfg.Message<OrderPlaced>(x => x.SetEntityName("order-placed-exchange"));
                    //cfg.Publish<OrderPlaced>(x => x.ExchangeType = "direct");
                });

            });


            var app = builder.Build();

            // Configure the HTTP request pipeline.
            if (app.Environment.IsDevelopment())
            {
                app.UseSwagger();
                app.UseSwaggerUI();
            }

            app.UseHttpsRedirection();

            app.UseAuthorization();

            app.MapPost("/orders", async (OrderDto order, IBus bus) =>
            {
                var orderPlacedMessage = new OrderPlaced(order.OrderId, order.Quantity);


                await bus.Publish(orderPlacedMessage, context =>
                {
                    context.SetRoutingKey("order.created");
                });

                return Results.Created($"/orders/{order.OrderId}", orderPlacedMessage);
            });
            app.MapControllers();

            app.Run();
        }
    }
}

public record OrderDto(Guid OrderId,int Quantity);
